<template>
  <div class="deviceInfo-page">
    <div class="search-field">
      <el-form :model="searchForm" inline>
        <el-form-item label="设备名称" prop="name">
          <el-input
            style="width: 200px"
            placeholder="请输入设备名称"
            v-model="searchForm.name"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="设备唯一识别" prop="sn">
          <el-input
            style="width: 200px"
            placeholder="请输入设备唯一识别"
            v-model="searchForm.sn"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="设备分类" prop="categoryId">
          <el-select
            style="width: 200px"
            v-model="searchForm.categoryId"
            placeholder="选择状态"
          >
            <el-option
              v-for="option in deviceCategoryList"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>

          <!-- <el-input
            placeholder="请输入设备分类"
            v-model="searchForm.categoryId"
            autocomplete="off"
          /> -->
        </el-form-item>
        <el-form-item label="所属门店" prop="storeId">
          <el-select-v2
            style="width: 200px"
            v-model="searchForm.storeId"
            placeholder="请选择门店"
            filterable
            :options="storeList"
            :props="{
              label: 'name',
              value: 'id',
            }"
          >
          </el-select-v2>

          <!-- <el-input
            placeholder="请输入所属门店"
            v-model="searchForm.storeId"
            autocomplete="off"
          /> -->
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            style="width: 200px"
            v-model="searchForm.status"
            placeholder="选择状态"
          >
            <el-option
              v-for="option in statusOptions"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <div>
            <el-button type="primary" @click="startSearch"> 查询 </el-button>
            <el-button @click="startClear"> 重置 </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-pagination-content">
      <div class="btns-fun-field">
        <!-- v-if="userPermission.addUserPerm" -->
        <el-button
          type="primary"
          @click.prevent="showAddEditDialog"
          :icon="Plus"
        >
          新增设备信息
        </el-button>
      </div>
      <div class="table-field">
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          v-loading="tableLoading"
        >
          <el-table-column prop="number" label="设备编码" width="120" />
          <el-table-column prop="categoryName" label="所属产品" width="90" />
          <el-table-column prop="productUrl" label="产品图" width="100">
            <template #default="scope">
              <el-image
                style="width: 60px; height: 60px"
                :src="scope.row.productUrl"
                :preview-src-list="[scope.row.productUrl]"
                fit="cover"
                :preview-teleported="true"
              >
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="设备名称" width="180" />
          <el-table-column prop="sn" label="设备唯一识别" width="180" />

          <el-table-column prop="storeName" label="所属门店" width="140" />
          <el-table-column prop="status" label="状态" width="90">
            <template #default="scope">
              <el-tag v-if="scope.row.status === 0" type="success">启动</el-tag>
              <el-tag v-else type="danger">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="是否部署" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.deployDate" type="success">已部署</el-tag>
              <el-tag v-else type="danger">待部署</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="deployDate" label="部署时间" width="170" />
          <el-table-column prop="deployCode" label="部署编码" width="140" />
          <el-table-column
            prop="softwareVersion"
            label="固件版本"
            width="120"
          />
          <el-table-column prop="remark" label="备注" width="190" />

          <el-table-column prop="createTime" label="创建时间" width="170" />
          <el-table-column prop="updateTime" label="更新时间" width="170" />

          <el-table-column label="操作" min-width="220px" fixed="right">
            <template #default="scope">
              <!-- v-if="rolePermission.editRolePerm" -->
              <el-button
                type="success"
                size="small"
                @click.prevent="showAddEditDialog(scope.row, 2)"
                >编辑</el-button
              >
              <!-- v-if="rolePermission.removeRolePerm" -->
              <el-button
                type="danger"
                size="small"
                @click.prevent="showRemoveDialog(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-field">
        <el-pagination
          v-model:current-page="formData.pageIndex"
          v-model:page-size="formData.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="formData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <DeviceInfoAdd v-model="addUpdateRef"></DeviceInfoAdd>
    <DeviceInfoRemove v-model="removeRef"></DeviceInfoRemove>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import {
  getDeviceInfoPagination,
  getDeviceInfoAllList,
} from '@/api/dms-device-info.api'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
// import { useUserPermission } from "@/utils/permission.utils";
import DeviceInfoRemove from './DeviceInfoRemove.vue'
import DeviceInfoAdd from './DeviceInfoAdd.vue'
import { getCanUseCode } from '@/api/fms-code-dict.api'
import {
  getDeviceCategoryPagination,
  getDeviceCategoryAllList,
} from '@/api/dms-device-category.api'
import { getStoreAllList } from '@/api/tms-store.api'
import { statusOptions } from '@/utils/common.utils'

const titleName = `设备信息`
// const userPermission = useUserPermission();

/****
 * =============== 新增、修改相关操作 =====================
 */
const addUpdateRef = reactive({
  visible: false,
  disabled: false,
  title: `设备信息`,
  curSelectRow: {},
  deviceCategoryList: [],
  storeList: [],
  form: {},
  rules: {},
  refreshDataList: () => {
    getDataList()
  },
})

const requestCanUseCode = () => {
  getCanUseCode({ type: 102 })
    .then((res: any) => {
      console.log('getCanUseCode: ', res)
      addUpdateRef.form.number = res
    })
    .catch((err) => {
      ElMessage.error(err.msg)
    })
}

/***
 * 机台保养设置
 */
const deviceSettingRef = reactive({
  visible: false,
  title: `机台保养设置`,
  curSelectRow: {},
  form: {},
  rules: {},
  refreshDataList: () => {
    getDataList()
  },
})
const showDeviceSettingDialog = () => {}

/***
 * 机台断网设置
 */
const lockNetworkRef = reactive({
  visible: false,
  title: `机台断网设置`,
  curSelectRow: {},
  form: {},
  rules: {},
  refreshDataList: () => {
    getDataList()
  },
})
const showLockNetworkDialog = () => {}

/***
 * 添加按钮
 */
const showAddEditDialog = (item: any, type: number) => {
  //新增
  if (item.target) {
    let form = {
      id: null,
      number: '',
      sn: '',
      name: '',
      categoryId: '',
      categoryName: '',
      storeId: '',
      storeName: '',
      remark: '',
      status: '',
      disabled: false,
    }
    addUpdateRef.visible = true
    addUpdateRef.disabled = false
    addUpdateRef.form = form
    requestCanUseCode()
    return
  }

  let form = {
    id: item.id,
    number: item.number,
    sn: item.sn,
    name: item.name,
    categoryId: item.categoryId,
    categoryName: item.categoryName,
    storeId: item.storeId,
    storeName: item.storeName,
    remark: item.remark,
    status: item.status,
    disabled: false,
  }
  addUpdateRef.visible = true
  addUpdateRef.disabled = true
  addUpdateRef.form = form
}

/****
 * =============== 删除操作 =====================
 */
const removeRef = reactive({
  visible: false,
  title: `设备信息`,
  curSelectRow: {},
  refreshDataList: () => {
    getDataList()
  },
})
const showRemoveDialog = (item: any) => {
  removeRef.visible = true
  removeRef.curSelectRow = item
}

/****
 * =============== 搜索、表格、分页 =====================
 */
const formData = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})

const searchForm = ref({
  number: '',
  sn: '',
  name: '',
  categoryId: '',
  categoryName: '',
  storeId: '',
  storeName: '',
  remark: '',
  status: '',
  deployDate: '',
  deployCode: '',
  softwareVersion: '',
})

const tableLoading = ref(false)
const tableData = ref([])
/***
 * 开始搜索
 */
const startSearch = () => {
  formData.pageIndex = 1
  getDataList()
}

/***
 * 重置搜索条件
 */
const startClear = () => {
  formData.pageIndex = 1
  let value = searchForm.value
  Object.keys(value).forEach((key) => {
    ;(value as any)[key] = ''
  })
  getDataList()
}

const handleSizeChange = (value: number) => {
  formData.pageSize = value
  getDataList()
}

const handleCurrentChange = (value: number) => {
  formData.pageIndex = value
  getDataList()
}

const getDataList = () => {
  let searchCondition: any = {}

  let number = searchForm.value.number
  if (number) {
    searchCondition.number = number
  }
  let sn = searchForm.value.sn
  if (sn) {
    searchCondition.sn = sn
  }
  let name = searchForm.value.name
  if (name) {
    searchCondition.name = name
  }
  let categoryId = searchForm.value.categoryId
  if (categoryId) {
    searchCondition.categoryId = categoryId
  }
  let categoryName = searchForm.value.categoryName
  if (categoryName) {
    searchCondition.categoryName = categoryName
  }
  let storeId = searchForm.value.storeId
  if (storeId) {
    searchCondition.storeId = storeId
  }
  let storeName = searchForm.value.storeName
  if (storeName) {
    searchCondition.storeName = storeName
  }
  let remark = searchForm.value.remark
  if (remark) {
    searchCondition.remark = remark
  }
  let status = searchForm.value.status
  if (status) {
    searchCondition.status = status
  }
  let deployDate = searchForm.value.deployDate
  if (deployDate) {
    searchCondition.deployDate = deployDate
  }
  let deployCode = searchForm.value.deployCode
  if (deployCode) {
    searchCondition.deployCode = deployCode
  }
  let softwareVersion = searchForm.value.softwareVersion
  if (softwareVersion) {
    searchCondition.softwareVersion = softwareVersion
  }

  tableLoading.value = true
  getDeviceInfoPagination({
    pageSize: formData.pageSize,
    pageIndex: formData.pageIndex,
    ...searchCondition,
  })
    .then(function (res: any) {
      tableLoading.value = false
      console.log(res)
      tableData.value = res.list || []
      formData.total = Number(res.total)
    })
    .catch((error) => {
      console.log(error)
      tableLoading.value = false
    })
}

const deviceCategoryList = ref([])
const requestDeviceCategoryAllList = () => {
  getDeviceCategoryAllList({})
    .then((res: any) => {
      deviceCategoryList.value = res || []
      addUpdateRef.deviceCategoryList = deviceCategoryList.value
    })
    .catch((err: any) => {
      console.log(err)
    })
}

const storeList = ref([])
const requestStoreList = () => {
  getStoreAllList({})
    .then((res: any) => {
      storeList.value = res || []
      addUpdateRef.storeList = storeList.value
    })
    .catch((err) => {
      ElMessage.error(err.msg)
    })
}

onMounted(() => {
  requestDeviceCategoryAllList()
  requestStoreList()
  getDataList()
})
</script>
<style lang="scss" scoped>
.deviceInfo-page {
  height: 100%;
}

.btns-fun-field {
  margin-bottom: 20px;
}

.pagination-field {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}

.btn-inner {
  display: flex;
  justify-content: center;
  color: #fff;
}

.tag-field {
  .el-tag {
    margin-right: 5px;
    &:last-child {
      margin-right: 0;
    }
  }
}

.search-field {
  margin-bottom: 12px;
  background: #fff;
  padding: 20px 20px 0px 20px;
  border-radius: 8px;
}

.deviceInfo-page-content {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
}
</style>
